import baidubce
from baidubce import exception
from baidubce.auth import bce_credentials
from baidubce import bce_client_configuration
from baidubce.services.bos import bos_client

from django.conf import settings


def get_config(region):
    config = bce_client_configuration.BceClientConfiguration(
        credentials=bce_credentials.BceCredentials(
            access_key_id='de9d2aa13b584665883e765e4d7a86e3',
            secret_access_key='81b811a56e6248688cca5cada623a218',
        ),
        endpoint=region,
        protocol=baidubce.protocol.HTTPS
    )
    return config


def upload_file(bucket_name, obj_key, region='fsh.bcebos.com', file_obj=None):
    """ """
    config = get_config(region)

    # 获取客户端对象
    client = bos_client.BosClient(config)

    upload_id = client.initiate_multipart_upload(bucket_name, obj_key).upload_id


    left_size = file_obj.size

    # left_size用于设置分块开始位置
    # 设置分块的开始偏移位置
    offset = 0

    part_number = 1
    part_list = []

    while left_size > 0:
        # 设置每块为5MB
        part_size = 5 * 1024 * 1024
        if left_size < part_size:
            part_size = left_size

        response = client.upload_part_from_file(
            bucket_name=bucket_name,
            key=obj_key,
            upload_id=upload_id,
            part_number=part_number,
            part_size=part_size,
            offset=offset,
            file_obj=file_obj,
        )

        left_size -= part_size
        offset += part_size
        part_list.append({
            "partNumber": part_number,
            "eTag": response.metadata.etag
        })

        part_number += 1

    client.complete_multipart_upload(
        bucket_name=bucket_name,
        key=obj_key,
        upload_id=upload_id,
        part_list=part_list,
    )

    # https://bucket-baiduyun.fsh.bcebos.com/image-20200324102030227.png
    return 'https://{}.{}/{}'.format(bucket_name, region, obj_key)


def delete_file(bucket, obj_key, region='fsh.bcebos.com'):
    """ 删除单个文件 """
    config = get_config(region)

    # 获取客户端对象
    client = bos_client.BosClient(config)

    # 查看文件是否存在
    try:
        response = client.get_object_meta_data(bucket, obj_key)
        print("Get meta:{}", response.metadata)
    except exception.BceError as e:
        print(e)
    else:
        client.delete_object(bucket, obj_key)


def delete_file_list(bucket, key_list, region='fsh.bcebos.com'):
    """ 批量删除文件 """
    config = get_config(region)
    # 获取客户端对象
    client = bos_client.BosClient(config)
    client.delete_multiple_objects(bucket, key_list)


if __name__ == '__main__':
    delete_file_list('bucket-baiduyun',
                     ['image-20200403165439890.png', 'image-20200325144152628.png']
                     )